import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import MapView from '@arcgis/core/views/MapView'
import Map from '@arcgis/core/Map'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Query from '@arcgis/core/rest/support/Query'

// 导出选中的要素，供其他模块使用
export let selectedFeature: Graphic | null = null

// 地块属性表单
export const landParcelForm = reactive({
  FID: null as number | null,
  LandID: '',
  landType: '',
  Area: 0,
  landUse: '',
  ownershipType: '',
  rightHolder: '',
  expirationDate: '',
  acquisitionDate: '',
  updateDate: '',
  parcelStatus: '',
  parcelGrade: '',
  remarks: '',
})

// 地块查询状态
export const queryState = reactive({
  showAttributePanel: false,
  isQuerying: false,
  multipleResults: [] as any[],
  showResultsDialog: false,
})
let multipleResultsFeatures: Graphic[] | null = null
// 重置表单
export const resetForm = () => {
  landParcelForm.FID = null
  landParcelForm.LandID = ''
  landParcelForm.landType = ''
  landParcelForm.Area = 0
  landParcelForm.landUse = ''
  landParcelForm.ownershipType = ''
  landParcelForm.rightHolder = ''
  landParcelForm.expirationDate = ''
  landParcelForm.acquisitionDate = ''
  landParcelForm.updateDate = ''
  landParcelForm.parcelStatus = ''
  landParcelForm.parcelGrade = ''
  landParcelForm.remarks = ''
}

// 地块类型选项
export const landTypeOptions = [
  { label: '耕地', value: '耕地' },
  { label: '林地', value: '林地' },
  { label: '草地', value: '草地' },
  { label: '住宅用地', value: '住宅用地' },
  { label: '商业用地', value: '商业用地' },
  { label: '工业用地', value: '工业用地' },
  { label: '交通用地', value: '交通用地' },
  { label: '水域', value: '水域' },
  { label: '其他', value: '其他' },
]

// 地图浏览查询功能
export function useParcelQuery(mapView: MapView | null, map: Map | null) {
  let landParcelLayer: FeatureLayer | null = null
  // 添加一个变量来跟踪事件监听器是否已添加
  let clickEventAdded = false

  // 初始化地图查询功能
  const initMapQuery = (mapInstance?: { map: Map; mapView: MapView } | null) => {
    // 如果传入了地图实例，则使用传入的地图实例
    if (mapInstance) {
      map = mapInstance.map
      mapView = mapInstance.mapView
    }

    if (!mapView || !map) return

    // 获取地块图层
    landParcelLayer = map.findLayerById('landParcelLayer') as FeatureLayer
    if (!landParcelLayer) {
      console.error('找不到地块图层')
      return
    }

    // 确保只添加一次点击事件监听器
    if (!clickEventAdded && mapView) {
      // 监听点击事件，用于查询地块信息
      mapView.on('click', async (event) => {
        // 如果正在查询，不执行新的查询
        if (queryState.isQuerying) return

        queryState.isQuerying = true

        try {
          // 转换空间参考
          const mapPoint = event.mapPoint
          // 创建查询对象
          const query = new Query()
          query.geometry = mapPoint
          query.distance = 10 // 增加点击容差
          query.units = 'meters'
          query.spatialRelationship = 'intersects'
          query.returnGeometry = true
          query.outFields = ['*']

          // 查询地块图层
          if (landParcelLayer && landParcelLayer.visible) {
            // 强制刷新图层
            landParcelLayer.refresh()
            const result = await landParcelLayer.queryFeatures(query)

            if (result.features.length > 0) {
              const feature = result.features[0]
              selectedFeature = feature

              // 填充表单数据
              const attributes = feature.attributes
              landParcelForm.FID = attributes.FID
              landParcelForm.LandID = attributes.LandID || ''
              landParcelForm.landType = attributes.landType || ''
              landParcelForm.Area = attributes.Shape__Area || 0
              landParcelForm.landUse = attributes.landUse || ''
              landParcelForm.ownershipType = attributes.ownershipType || ''
              landParcelForm.rightHolder = attributes.rightHolder || ''
              landParcelForm.expirationDate = attributes.expirationDate || ''
              landParcelForm.acquisitionDate = attributes.acquisitionDate || ''
              landParcelForm.updateDate = attributes.updateDate || ''
              landParcelForm.parcelStatus = attributes.parcelStatus || ''
              landParcelForm.parcelGrade = attributes.parcelGrade || ''
              landParcelForm.remarks = attributes.remarks || ''

              // 显示属性面板
              queryState.showAttributePanel = true
            } else {
              // 如果没有选中要素，隐藏属性面板
              selectedFeature = null
              queryState.showAttributePanel = false
              resetForm()
            }
          }
        } catch (error) {
          console.error('查询地块失败:', error)
          ElMessage.error('查询地块失败')
        } finally {
          queryState.isQuerying = false
        }
      })

      // 标记事件已添加
      clickEventAdded = true
    }
  }

  // 关闭属性面板
  const closeAttributePanel = () => {
    queryState.showAttributePanel = false
    selectedFeature = null
    resetForm()
  }

  // 根据属性查询地块
  const queryParcelByAttribute = async (params: { landId?: string; landUse?: string }) => {
    // 获取地块图层
    landParcelLayer = map!.findLayerById('landParcelLayer') as FeatureLayer
    if (!landParcelLayer) {
      ElMessage.error('找不到地块图层')
      return
    }

    queryState.isQuerying = true

    try {
      // 创建查询对象
      const query = new Query()
      query.returnGeometry = true
      query.outFields = ['*']

      // 构建查询条件
      let whereClause = '1=1'

      if (params.landId && params.landId.trim() !== '') {
        whereClause += ` AND LandID LIKE '%${params.landId}%'`
      }

      if (params.landUse && params.landUse.trim() !== '') {
        whereClause += ` AND landUse = '${params.landUse}'`
      }

      query.where = whereClause

      // 执行查询
      const result = await landParcelLayer.queryFeatures(query)

      if (result.features.length === 0) {
        ElMessage.info('未找到符合条件的地块')
        queryState.showAttributePanel = false
        resetForm()
        return
      }

      // 如果只有一个结果，直接显示
      if (result.features.length === 1) {
        multipleResultsFeatures  = result.features
        displayFeature(0)
        return
      }

      // 如果有多个结果，弹出选择框
      showMultipleResultsDialog(result.features)
    } catch (error) {
      console.error('查询地块失败:', error)
      ElMessage.error('查询地块失败')
    } finally {
      queryState.isQuerying = false
    }
  }

  // 显示地块特征
  const displayFeature = async (index : number) => {
    let feature = multipleResultsFeatures![index]
    selectedFeature = feature
    // 填充表单数据
    const attributes = feature.attributes
    console.log(attributes)
    landParcelForm.FID = attributes.FID
    landParcelForm.LandID = attributes.LandID || ''
    landParcelForm.landType = attributes.landType || ''
    landParcelForm.Area = attributes.Shape__Area || 0
    landParcelForm.landUse = attributes.landUse || ''
    landParcelForm.ownershipType = attributes.ownershipType || ''
    landParcelForm.rightHolder = attributes.rightHolder || ''
    landParcelForm.expirationDate = attributes.expirationDate || ''
    landParcelForm.acquisitionDate = attributes.acquisitionDate || ''
    landParcelForm.updateDate = attributes.updateDate || ''
    landParcelForm.parcelStatus = attributes.parcelStatus || ''
    landParcelForm.parcelGrade = attributes.parcelGrade || ''
    landParcelForm.remarks = attributes.remarks || ''

    // 显示属性面板
    queryState.showAttributePanel = true

    // 缩放到选中的地块
    if (mapView && feature.geometry) {
      await mapView.goTo(feature.geometry)
      mapView.zoom = 13
    }
  }

  // 显示多个结果选择对话框
  const showMultipleResultsDialog = (features: Graphic[]) => {
    // 清空之前的结果
    queryState.multipleResults = []
    multipleResultsFeatures = features

    // 准备选项数据
    const options = features.map((feature, index) => {
      const attrs = feature.attributes
      return {
        value: index,
        label: `地块编号: ${attrs.LandID || '未知'} - 土地用途: ${attrs.landUse || '未知'}`,
        feature: feature, // 确保包含 feature 对象
      }
    })

    // 将结果保存到状态中，供对话框使用
    queryState.multipleResults = options
    queryState.showResultsDialog = true
  }

  // 点击地图查询地块
  const query = async (mapPoint: any) => {
    if (!landParcelLayer) return

    queryState.isQuerying = true

    try {
      // 创建查询对象
      const query = new Query()
      query.geometry = mapPoint
      query.distance = 10 // 增加点击容差
      query.units = 'meters'
      query.spatialRelationship = 'intersects'
      query.returnGeometry = true
      query.outFields = ['*']

      // 查询地块图层
      if (landParcelLayer && landParcelLayer.visible) {
        // 强制刷新图层
        landParcelLayer.refresh()
        const result = await landParcelLayer.queryFeatures(query)

        if (result.features.length > 0) {
          displayFeature(0)
        } else {
          // 如果没有选中要素，隐藏属性面板
          selectedFeature = null
          queryState.showAttributePanel = false
          resetForm()
        }
      }
    } catch (error) {
      console.error('查询地块失败:', error)
      ElMessage.error('查询地块失败')
    } finally {
      queryState.isQuerying = false
    }
  }

  // 在 useParcelQuery 函数的返回值中添加 displayFeature
  return {
    initMapQuery,
    closeAttributePanel,
    queryParcelByAttribute,
    query,
    displayFeature,
    landParcelForm,
    queryState,
    landTypeOptions,
  }
}
